package com.cash.channel.web.mq;

import com.alibaba.fastjson.JSON;
import com.cash.channel.api.constant.Constant;
import com.cash.channel.api.model.callback.RepayPlanListCallBack;
import com.cash.channel.web.logic.CallBackLogic;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class RepayPlanSynListener {

    @Autowired
    private CallBackLogic callBackLogic;

    @RabbitListener(containerFactory = "rabbitListenerContainerFactory", bindings = {
            @QueueBinding(
                    // 绑定queue
                    value = @Queue(value = Constant.ProConstant.CHANNEL_REPAY_PLAN_SYN_CALLBACK, durable = "true", autoDelete = "false"),
                    // 绑定exchange
                    exchange = @Exchange(value = "geex", durable = "true"),
                    key = Constant.ProConstant.CHANNEL_REPAY_PLAN_SYN_CALLBACK)})
    public void receiveChannelProtocol(Channel channel, Message message) {
        try {
            // 实体接收
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
            // 字符串接收
            log.info("收到还款计划表同步队列：" + message);
            RepayPlanListCallBack map = objectMapper.readValue(message.getBody(), RepayPlanListCallBack.class);
            log.info("收到还款计划表同步队列 map:" + map.toString());
            try {
                if (map != null) {
                    Integer isCustom = map.getIsCustom();
                    if (0 == isCustom) {
                        RepayPlanListCallBack callBack = objectMapper.readValue(message.getBody(), RepayPlanListCallBack.class);
                        log.info("获取还款计划表同步队列信息："+ JSON.toJSONString(callBack));
                        callBackLogic.commonRepayPlanSynCallBack(map.getChannel(), callBack);
                    } else {
                        // TODO: 2019/11/5 第三方
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw e;
            }

        } catch (Exception ex) {
            log.info("receiveChannelBindCard error:");
            log.error(ex.getMessage(), ex);
        }
    }

}
